﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.BD
{
    public partial class UserAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {

                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        public void GetUserList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                listSearch.Add(new SearchCondition() { Field = "UserState", Operator = "=", Value = "0" });

            }
            Expression<Func<View_BD_UserDepInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_UserDepInfo>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_BD_UserDepInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.Order);
            var userIdList = list.Select(s => s.ID).ToList();
            var userRole = DALSession.Current.BD_UserRoleDAL.GetListBy(r => userIdList.Contains(r.UId)).ToList();
            var roleIdList = userRole.Select(r => r.RId).ToList();
            var roleList = DALSession.Current.BD_RoleDAL.GetListBy(r => roleIdList.Contains(r.Id)).ToList();
            foreach (var item in list)
            {
                var userRoleIdList = userRole.Where(r => r.UId == item.ID).Select(r => r.RId).ToList();
                var RoleNameList = roleList.Where(r => userRoleIdList.Contains(r.Id)).ToList();
                string roleName = "";
                foreach (var roleNameItem in RoleNameList)
                {
                    roleName += roleNameItem.Name + ",";
                }
                string a = roleName.TrimEnd(',');
                item.RoleName = a;
            }
            count = DALSession.Current.View_BD_UserDepInfoDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }


        /// <summary>
        /// 根据q获取人员信息
        /// </summary>
        public void GetClassUserInfoByQ()
        {
            string q = Request.Form["q"];
            int intQ = Commons.String2Int32(q);
            var a = DALSession.Current.View_BD_UserDepInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, m => (m.ID == intQ || m.UserName.Contains(q)  || m.DepName.Contains(q)) , "ID", OperateContext.OrderDesc).Select(m => new { value = m.ID, text = m.UserName, DepName = m.DepName, DepId = m.DepId,UserState = m.UserState });
            int count = DALSession.Current.View_BD_UserDepInfoDAL.GetCount(m => (m.ID == intQ || m.UserName.Contains(q) || m.DepName.Contains(q)) );
            Response.Write(JsonHelper.toPageJson(a, count));
            //&& m.FatherId == 4,, && m.FatherId == 4
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        public void EditUser()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            BD_UserInfo perNew = DALSession.Current.BD_UserInfoDAL.GetListBy(d => d.ID == ID).FirstOrDefault();

            ModelTools.Form2EditModel(Request.Form, perNew);
            perNew.ManClerk = OperateContext.SessBasicInfo.UserInfo.Name.ToString();
            perNew.FillDate = DateTime.Now.ToString("yyyy-MM-dd");
            DALSession.Current.BD_UserInfoDAL.ModifyAllModel(perNew);
            DALSession.Current.BD_UserInfoDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        /// <summary>
        /// 添加用户信息
        /// </summary>
        public void AddUser()
        {
            BD_UserInfo per = new BD_UserInfo();
            ModelTools.Form2EditModel(Request.Form, per);
            per.ManClerk = OperateContext.SessBasicInfo.UserInfo.Name.ToString();
            per.FillDate = DateTime.Now.ToString("yyyy-MM-dd");
            per.PassWord = "123456";
            DALSession.Current.BD_UserInfoDAL.Add(per);
            DALSession.Current.BD_UserInfoDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        /// <summary>
        /// 暂停用户信息
        /// </summary>
        public void DelUser()
        {

            //  int Id = Commons.String2Int32(Request.Form["Id"]);
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            DALSession.Current.BD_UserInfoDAL.DelBy(u => u.ID == Id);
            DALSession.Current.BD_UserInfoDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }
        /// <summary>
        /// 获取用户角色
        /// </summary>
        public void GetUserRole()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<BD_Role> roleList = Permission.GetAllRole(userId);
            List<int> roleIdList = DALSession.Current.BD_UserRoleDAL.GetListBy(p => p.UId == userId).Select(u => u.RId).ToList();
            List<CheckboxList> cblist = new List<CheckboxList>();
            foreach (var item in roleList)
            {
                if (roleIdList.Contains(item.Id))
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = true });
                }
                else
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = false });
                }
            }

            Response.Write(JsonHelper.toJson(cblist));
        }
        /// <summary>
        /// 修改用户角色
        /// </summary>
        public void EditUserRole()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<int> checkrole = new List<int>();
            string roleids = Request.Form["RoleIds"].ToString();
            for (int i = 0; i < roleids.Trim(',').Split(',').Length; i++)
            {
                checkrole.Add(Commons.String2Int32(roleids.Trim(',').Split(',')[i]));
            }
            DALSession.Current.BD_UserRoleDAL.DelBy(p => p.UId == userId);
            foreach (var urId in checkrole)
            {
                DALSession.Current.BD_UserRoleDAL.Add(new BD_UserRole() { RId = urId, UId = userId });
            }
            DALSession.Current.BD_UserRoleDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));

        }
        /// <summary>
        /// 获取用户页面链接特权
        /// </summary>
        public void GetUserLinkTree()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<BD_Permission> perm = Permission.GetAllLink();
            List<BD_UserVipPermission> userPerm = Permission.GetPermByUserid(userId);
            List<TreeNode> node = Permission.GetPerTreeBySubTreeUserid(perm, userPerm);
            string nodeStr = JsonHelper.toJson(node);
            string newNodeStr = nodeStr.Replace("Checked", "checked");
            Response.Write(JsonHelper.toJson(newNodeStr));
        }
        /// <summary>
        /// 修改用户页面链接特权
        /// </summary>
        public void EditUserLinkTree()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<int> nodes = new List<int>();
            string nodesStr = Request.Form["PermIds"].ToString();
            for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
            {
                nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
            }
            DALSession.Current.BD_UserVipPermissionDAL.DelBy(p => p.vipUserId == userId);
            foreach (var pId in nodes)
            {
                DALSession.Current.BD_UserVipPermissionDAL.Add(new BD_UserVipPermission() { vipPermission = pId, vipUserId = userId });
            }
            DALSession.Current.BD_UserVipPermissionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));

        }
        //获取用户的权限按钮的树节点
        public void GetUserBtnPer()
        {
            //获取用户的ID
            int userId = Convert.ToInt32(Request.Form["Id"]);
            //获取用户的所有二级页面
            List<BD_Permission> UserPerm = Permission.GetPermByUserEr(userId);
            //获取该用户选中的按钮Id集合
            List<int> userBtnPerm = Permission.GetBtnPermIdListByUserid(userId);
            //获取用户所有二级页面下的按钮
            List<BD_btnPermission> allBtnPerm = Permission.GetAllBtnPermUser(UserPerm);
            //创建树节点
            List<TreeNode> node = Permission.GetBtnTreeUser(UserPerm, allBtnPerm, userBtnPerm);
            string nodeStr = JsonHelper.toJson(node).Replace("Checked", "checked");
            Response.Write(nodeStr);
        }
        //更改用户的权限按钮的树节点
        public void EditUserBtnPer()
        {
            //获取用户的ID
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<int> nodes = new List<int>();
            string nodesStr = Request.Form["PermIds"].ToString();
            for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
            {
                nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
            }
            DALSession.Current.BD_UserVipBtnPermissionDAL.DelBy(p => p.vipUserId == userId);
            foreach (var PId in nodes)
            {
                DALSession.Current.BD_UserVipBtnPermissionDAL.Add(new BD_UserVipBtnPermission() { vipUserId = userId, vipBtnPermission = PId });
            }
            DALSession.Current.BD_UserVipBtnPermissionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));
        }


        // 获取快捷登录列表
        public void GetShortCutList()
        {
            //获取所有快捷登录权限
            //  List<BD_Permission> perm = DALSession.Current.BD_PermissionDAL.GetListBy(p => p.IsShortCut == "0").ToList();
            List<BD_Permission> perm = OperateContext.SessPermission.Where(p => p.IsShortCut == "0").ToList();
            //获取本人快捷登录权限
            List<BD_Permission> mePerm = Permission.GetShortCutByMe();
            List<int> meIntList = mePerm.Select(m => m.Id).ToList();
            List<CheckboxList> cblist = new List<CheckboxList>();
            foreach (var item in perm)
            {
                if (meIntList.Contains(item.Id))
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = true });
                }
                else
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = false });
                }
            }

            Response.Write(JsonHelper.toJson(cblist));
        }
        /// <summary>
        /// 编辑个人快速导航菜单
        /// </summary>
        public void EditShortCut()
        {
            int userId = OperateContext.SessBasicInfo.UserInfo.Id;
            List<int> checkrole = new List<int>();
            string shortIds = Request.Form["ShortIds"].ToString();
            for (int i = 0; i < shortIds.Trim(',').Split(',').Length; i++)
            {
                checkrole.Add(Commons.String2Int32(shortIds.Trim(',').Split(',')[i]));
            }
            DALSession.Current.BD_UserShortCutDAL.DelBy(u => u.uId == userId);
            foreach (var urId in checkrole)
            {
                DALSession.Current.BD_UserShortCutDAL.Add(new BD_UserShortCut() { pId = urId, uId = userId });
            }
            DALSession.Current.BD_UserShortCutDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));
        }








        /// <summary>
        /// 获取我的授权信息列表
        /// </summary>
        public void GetPerAuthorList()
        {

            int userId = OperateContext.SessBasicInfo.UserInfo.Id;
            int count = 0;
            var list = DALSession.Current.View_BD_AuthorizeInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, a => a.FromUserId == userId || a.ToUserId == userId, "FillDate", OperateContext.OrderDesc);
            count = DALSession.Current.View_BD_AuthorizeInfoDAL.GetCount(a => a.FromUserId == userId || a.ToUserId == userId);
            Response.Write(JsonHelper.toPageJson(list, count));
        }



        public void GetAuthorList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            string nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
                }
                if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
                }
                if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault() != null)
                {
                    if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "0")
                    {
                        listSearch.Add(new SearchCondition() { Field = "StartTime", Operator = "str<=", Value = nowDate });
                        listSearch.Add(new SearchCondition() { Field = "EndTime", Operator = "str>=", Value = nowDate });
                    }
                    else if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "1")
                    {
                        listSearch.Add(new SearchCondition() { Field = "EndTime", Operator = "str<=", Value = nowDate });
                    }
                    else if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "2")
                    {
                        listSearch.Add(new SearchCondition() { Field = "StartTime", Operator = "str>=", Value = nowDate });
                    }
                }

            }
            Expression<Func<View_BD_AuthorizeInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_AuthorizeInfo>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_BD_AuthorizeInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
            count = DALSession.Current.View_BD_AuthorizeInfoDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        public void GetAuthorOperList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            string nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
                }
                if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
                }
            }
            Expression<Func<View_BD_AuthorizeOperInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_AuthorizeOperInfo>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_BD_AuthorizeOperInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
            count = DALSession.Current.View_BD_AuthorizeOperInfoDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));

        }



    }
}